package com.huike.web.controller.system;

import com.huike.clues.domain.SysMenu;
import com.huike.clues.result.RoleMenuTreeAjaxResult;
import com.huike.clues.service.ISysMenuService;
import com.huike.common.annotation.Log;
import com.huike.common.constant.Constants;
import com.huike.common.constant.UserConstants;
import com.huike.common.core.controller.BaseController;
import com.huike.common.core.domain.AjaxResult;
import com.huike.common.core.domain.entity.SysMenuDTO;
import com.huike.common.core.domain.model.LoginUser;
import com.huike.common.enums.BusinessType;
import com.huike.common.utils.SecurityUtils;
import com.huike.common.utils.ServletUtils;
import com.huike.common.utils.StringUtils;
import com.huike.framework.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Api(tags = "菜单信息相关接口")
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {

    @Resource
    private ISysMenuService menuService;

    @Resource
    private TokenService tokenService;

    @ApiOperation("获取菜单列表")
    @GetMapping("/list")
    public AjaxResult list(SysMenuDTO menu){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        List<SysMenuDTO> menus = menuService.selectMenuList(menu,userId);
        return AjaxResult.success(menus);
    }

    /**
     * 菜单编号详情(数据反显)
     * @param menuId
     * @return
     */
    @ApiOperation("根据菜单编号获取详细信息")
    @GetMapping("/{menuId}")
    public AjaxResult getMenuId(@PathVariable Long menuId){
        SysMenuDTO menu = menuService.getMenuId(menuId);
        return AjaxResult.success(menu);
    }

    @ApiOperation("获取菜单下拉树列表")
    @GetMapping("/treeselect")
    public AjaxResult getTreeselect(SysMenuDTO menu){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        List<SysMenuDTO> menus = menuService.selectMenuList(menu, userId);
        return AjaxResult.success(menuService.buildMenuTreeSelect(menus));
    }

    @ApiOperation("新增菜单")
    @PostMapping
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    public AjaxResult addMenu(@RequestBody SysMenuDTO menu){
        if(UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))){
            return AjaxResult.error("新增菜单'" + menu.getMenuName() +"' 失败,菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP,Constants.HTTPS)){
            return AjaxResult.error("新增菜单'" + menu.getMenuName() +"' 失败,地址必须以http(s)://开头");
        }
        menu.setCreateBy(SecurityUtils.getUsername());
        return toAjax(menuService.addMenu(menu));
    }

    @ApiOperation("修改菜单")
    @PutMapping
    public AjaxResult updateMenu(@RequestBody SysMenuDTO menu){
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
        {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS))
        {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        else if (menu.getMenuId().equals(menu.getParentId()))
        {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(menuService.updateMenu(menu));
    }

    @ApiOperation("加载对应角色菜单")
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public RoleMenuTreeAjaxResult menuRoleId(@PathVariable("roleId") Long roleId){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        List<SysMenuDTO> menus = menuService.selectMenuList(loginUser.getUser().getUserId());
        RoleMenuTreeAjaxResult ajax = RoleMenuTreeAjaxResult.success();
        ajax.setCheckedKeys(menuService.selectMenuListByRoleId(roleId));
        ajax.setMenus(menuService.buildMenuTreeSelect(menus));
        return ajax;
    }

    @ApiOperation("删除菜单")
    @DeleteMapping("/{menuId}")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    public AjaxResult delectMenuId(@PathVariable("menuId") Long menuId){
        //存在子菜单或已分配,不允许删除
        if(menuService.hasChildByMenuId(menuId)){
            return AjaxResult.error("存在子菜单,不允许删除");
        }
        if(menuService.checkMenuExistRole(menuId)){
            return AjaxResult.error("菜单已分配,不允许删除");
        }
        return toAjax(menuService.delectMenuId(menuId));
    }

}
